package com.atguigu.aclservice.controller;

import com.atguigu.aclservice.entity.User;
import com.atguigu.aclservice.entity.vo.LoginVo;
import com.atguigu.aclservice.entity.vo.RouterVo;
import com.atguigu.aclservice.service.MenuService;
import com.atguigu.aclservice.service.UserService;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.MD5;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author fxy
 * @date 2022/7/21 17:08
 */
@RestController
@RequestMapping("/acl/user")
//@CrossOrigin
@Slf4j
@Api(value = "后台管理系统登录", tags = "后台管理系统登录")
@Transactional
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //login

    @ApiOperation("后台管理系统登录并返回用户信息token")
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) throws Exception {

        log.info("loginVo"+loginVo.toString());

        String password = loginVo.getPassword();

        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",loginVo.getUsername());

        User user = userService.getOne(wrapper);

//        String redisCode = redisTemplate.opsForValue().get("code");
//        log.info("验证码=>>>>>>>>>>>>>"+redisCode);
//        if (!loginVo.getCode().equals(redisCode)){
//            throw new GuliException(20001,"验证码错误，请重新输入");
//        }

        if (user==null){
            throw new GuliException(20001,"用户不存在，请重新输入！！");
        }

        if (!user.getPassword().equals(MD5.encrypt(password))){
            throw new GuliException(20001,"登录失败,账号或密码错误！！");
        }

        if (user.getStatus()==0){
            throw new GuliException(20001,"登陆失败,账号被禁用，请联系管理员！！");
        }

        //添加登录时间和ip

        InetAddress address = InetAddress.getLocalHost();
//            userService.updateLoginTimeAndIp(user.getId(), new Date(),address.getHostAddress());


//        String token = "22";
        String token = JwtUtils.getJwtTokenForRole(user.getId(),user.getUsername());

        return R.ok().data("token",token);


    }

    //info
    @ApiOperation("根据token获取用户信息")
    @GetMapping("/info")
    public R info(HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtils.getRoleByJwtToken(token);
        User user = userService.getById(userId);
        //根据用户id查询菜单权限值
        List<RouterVo> routerVoList = menuService.getUserMenuList(user.getId());
        //根据用户id查询按钮权限值
        List<String> permsList = menuService.getUserButtonList(user.getId());
        return R.ok().data("name",user.getUsername()).data("avatar",user.getHeadUrl()).data("roles","[\"admin\"]").data("routers",routerVoList).data("buttons",permsList);

    }
}
